最近项目需要用Spring搭建一个Restful API项目,因此重拾了很久没用的JAVA,发现Spring多了一个SpringBoot项目,集成了嵌入式Tomcat,Jetty容器,无需部署WAR包,Mybatis也有类似的与Spring集成的东西,叫 mybatis-spring-boot ,这两个可以免除写一堆XML配置文件,以前写JAVA痛苦的XML配置过程不堪回首,所以干脆用这个搭一个吧。其实官方给的例子已经很详细了,下面是搭建的经验,懂的可以不用看了。
官方链接:
- 建立Maven项目,我用的是IDEA
复制pom.xml,添加依赖文件
<?xml version=”1.0” encoding=”UTF-8”?>
<project xmlns=”http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>visoon</groupId>
<artifactId>visoon</artifactId>
<version>1.0-SNAPSHOT</version><parent>
<groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.2.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version>
</properties>
<dependencies>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.0.0</version> </dependency> <!--mysql--> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
</dependencies>
<build>
<plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins>
</build>
<repositories>
<repository> <id>spring-releases</id> <url>https://repo.spring.io/libs-release</url> </repository>
</repositories>
<pluginRepositories><pluginRepository> <id>spring-releases</id> <url>https://repo.spring.io/libs-release</url> </pluginRepository>
</pluginRepositories>
</project>
- 一般项目结构是这样的:
- 编写Application.java
package cn.visoon;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
@EnableAutoConfiguration
@SpringBootApplication
@ComponentScan
@MapperScan(“cn.visoon.wechat.mapper”)
public class Application {
private static Logger logger = Logger.getLogger(Application.class);
@Bean
@ConfigurationProperties(prefix="spring.datasource")
public DataSource dataSource() {
return new org.apache.tomcat.jdbc.pool.DataSource();
}
@Bean
public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource());
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis/*.xml"));
return sqlSessionFactoryBean.getObject();
}
@Bean
public PlatformTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
- 编写User.java
package cn.visoon.wechat.model;
public class User {
private Integer id;
private String name;
private Integer age;
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
- 编写UserService.java
package cn.visoon.wechat.service;
import cn.visoon.wechat.mapper.UserMapper;
import cn.visoon.wechat.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUserInfo() {
User user = userMapper.findUserInfo();
return user;
}
}
- 编写UserMapper.java
package cn.visoon.wechat.mapper;
import cn.visoon.wechat.model.User;
public interface UserMapper {
public User findUserInfo();
}
- 编写UserController.java
package cn.visoon.wechat.controller;
import cn.visoon.wechat.model.User;
import cn.visoon.wechat.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.atomic.AtomicLong;
@RestController
public class UserController {
private Logger logger = Logger.getLogger(UserController.class);
@Autowired
private UserService userService;
@RequestMapping("/getUser")
public User getUser() {
User user = userService.getUserInfo();
if (user != null) {
logger.info("user.getId():" + user.getId());
logger.info("user.getAge():" + user.getAge());
logger.info("user.getName():" + user.getName());
}
return user;
}
}
- 配置数据库
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=gbk&zeroDateTimeBehavior=convertToNull
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
- 配置log4j
#config root logger
log4j.rootLogger = INFO,system.out
log4j.appender.system.out=org.apache.log4j.ConsoleAppender
log4j.appender.system.out.layout=org.apache.log4j.PatternLayout
log4j.appender.system.out.layout.ConversionPattern=[Log] %5p[%F:%L]:%m%n
#config this Project.file logger
log4j.logger.thisProject.file=INFO,thisProject.file.out
log4j.appender.thisProject.file.out=org.apache.log4j.DailyRollingFileAppender
log4j.appender.thisProject.file.out.File=logContentFile.log
log4j.appender.thisProject.file.out.layout=org.apache.log4j.PatternLayout
配置查询SQL。UserMapper.xml
<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE mapper PUBLIC “-//mybatis.org//DTD Mapper 3.0//EN” “http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace=”cn.visoon.wechat.mapper.UserMapper”><select id=”findUserInfo” resultType=”cn.visoon.wechat.model.User”>
select id, name, age,password from user;
</select>
</mapper>
- 最后,运行Application.java,像运行java应用程序一样。程序就跑起来了~